/*
 * Created on Mar 3, 2004
 */
package com.scalar.chiptrack.operations.packingslip.actions;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;
import org.apache.struts.util.MessageResources;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.ClientInfo;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.CustomerShippingLineItems;
import com.scalar.chiptrack.operations.packingslip.CustomerShippingLotNumberData;
import com.scalar.chiptrack.operations.packingslip.FinalInventoryData;
import com.scalar.chiptrack.operations.packingslip.dao.NewPackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.PackingSlipForm;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.chiptrack.utils.StringUtils;

/**
 * @author Ravikanth
**/
public class NewPackingSlipAction  extends ChipTrackAction
{

	public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		String action = request.getParameter("action");

        //Start here Added by Krishna Prasad 13 July 2004

        request.setAttribute ( "AUTO_CONFIRM_PACKING_SLIP" , request.getParameter ("autoConfirmPackingSlip") );

        User user = (User) session.getAttribute (SessionKeys.USER_KEY);

        String isRequestFromTrackingNoPage = (String) request.getParameter ( "isReqFromTrackingNoPage" ); //Added by Krishna Prasad on 07 May 2004
        if ( ( isRequestFromTrackingNoPage != null ) && ( isRequestFromTrackingNoPage.equals ( "true" ) ) ) //Added by Krishna Prasad on 07 June 2004, when request comes from PS Freight Tracking No. Page.
        {
            if( user == null )
            {
                user = new User ();
                user.setUserId ( "vendor" );
                user.setEmail ( ConfigManager.getSysAdminEmail() );
                session.setAttribute ( SessionKeys.USER_KEY , user );
            }
        }

		if (user == null)
		{
            if ( action.equalsIgnoreCase("view") )   // Added by Krishna 12 July 2004
            {
                PackingSlipForm packingSlipForm = ( PackingSlipForm ) form;
                if( packingSlipForm != null && ( packingSlipForm.isCancelPackingSlip() || packingSlipForm.isConfrimPackingSlip() ) )
                {
                    session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY , "/searchPackingSlip.do" );
                }
                else
                {
                    session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY , "/packingSlip.do?" + request.getQueryString());
                }
            }
            else if ( action.equalsIgnoreCase("confirmPackingSlip") || action.equalsIgnoreCase("cancelPackingSlip")  )
            {
                  session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY , "/searchPackingSlip.do" );
            }
            else
            {
			    session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY , "/packingSlip.do?" + request.getQueryString());
            }
            if( action.equalsIgnoreCase( "EditShippingAddress") || action.equalsIgnoreCase( "AddShippingAddress") || action.equalsIgnoreCase( "SaveShippingAddress") )
		    {
                request.setAttribute ( "closeWindowAfterSessionExp", "true" );
                return ( mapping.findForward("showShippingAddress") );
            }
			else
            {
                return ( mapping.findForward("login") );
            }
        }
        // Ends Here

		if( action.equalsIgnoreCase( "loadSalesOrder" ) )
		{
			return new GeneratePackingSlipAction().execute( mapping, form, request, response );
		}
		else if( action.equalsIgnoreCase( "save" ) )
		{
			return new SavePackingSlipAction().execute( mapping, form, request, response );
		}
		else if	( ( "view".equalsIgnoreCase ( action ) ) || ( "viewShipped".equalsIgnoreCase ( action ) ) )
		{
            String returnVal = "";
			PackingSlipForm packingSlipForm = ( PackingSlipForm )form;
            request.setAttribute( "weightMeasurementList", NewPackingSlipDAO.loadWeightMeasurements() );
			request.setAttribute( "uomPgkDimensionList", NewPackingSlipDAO.loadUomPkgDimensionList() );

            if( packingSlipForm.isCancelPackingSlip() )
			{
                ClientInfo clientInfo = UserDAO.getClientAddressInfo();
                packingSlipForm.setFinalInventoryDataMap( NewPackingSlipDAO.loadLotNumberDataByCustomerShippingId( packingSlipForm.getCustomerShippingId() ) );
                if( session.getAttribute( SessionKeys.FINAL_INVENTORY_MAP ) != null)
				{
                    HashMap InventoryDataMapDB          = NewPackingSlipDAO.loadLotNumberDataByCustomerShippingId( packingSlipForm.getCustomerShippingId() ) ;
                    HashMap existingInventoryDataMap    = getFinalInventoryMapByCustomerShippingId ( (HashMap)session.getAttribute( SessionKeys.FINAL_INVENTORY_MAP ) );
                    packingSlipForm.setFinalInventoryDataMapView( loadNewFinalInventoryDataListMap ( existingInventoryDataMap , InventoryDataMapDB ) );
				}
				else
				{
                    packingSlipForm.setFinalInventoryDataMapView( packingSlipForm.getFinalInventoryDataMap() );
				}

               request.setAttribute ( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList () );
               packingSlipForm.setClientInfo( clientInfo );
               returnVal = "packingSlipView" ;
               return( mapping.findForward( returnVal ) );
			}
			else if ( packingSlipForm.isConfrimPackingSlip() )
			{
				ClientInfo clientInfo = UserDAO.getClientAddressInfo();
				// this particular code needs to be changed
				// we need to use the same finalInventoryMap we had in session
				if( session.getAttribute( SessionKeys.FINAL_INVENTORY_MAP ) != null)
				{
                    HashMap InventoryDataMapDB          = NewPackingSlipDAO.loadLotNumberDataByCustomerShippingId( packingSlipForm.getCustomerShippingId() ) ;
                    HashMap existingInventoryDataMap    = getFinalInventoryMapByCustomerShippingId ( (HashMap) session.getAttribute( SessionKeys.FINAL_INVENTORY_MAP ) );
					packingSlipForm.setFinalInventoryDataMap( getFinalInventoryMapByCustomerShippingId( (HashMap)session.getAttribute( SessionKeys.FINAL_INVENTORY_MAP ) ) );
                    packingSlipForm.setFinalInventoryDataMapView( loadNewFinalInventoryDataListMap ( existingInventoryDataMap , InventoryDataMapDB ) );
				}
				else
				{
					packingSlipForm.setFinalInventoryDataMap( NewPackingSlipDAO.loadLotNumberDataByCustomerShippingId( packingSlipForm.getCustomerShippingId() ) );
                    packingSlipForm.setFinalInventoryDataMapView( packingSlipForm.getFinalInventoryDataMap() );
				}
                request.setAttribute ( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList () );
                packingSlipForm.setClientInfo( clientInfo );
                returnVal = "packingSlipView" ;
                return ( mapping.findForward ( returnVal ) );
			}

			return new ViewPackingSlipAction().execute( mapping, form, request, response );
		}
		else if( ( "printView".equalsIgnoreCase ( action ) ) || ( "labelView".equalsIgnoreCase ( action ) ) )
		{
			return new PrintPackingSlipAction().execute( mapping, form, request, response );
		}
		else if( action.equalsIgnoreCase( "confirmPackingSlip" ) )
		{
			return new ConfirmPackingSlipAction().execute( mapping, form, request, response );
		}
		else if( action.equalsIgnoreCase( "cancelPackingSlip" ) )
		{
			return new CancelPackingSlipAction().execute( mapping, form, request, response );
		}
		//else if( action.equalsIgnoreCase( "update" ) )
		else if( action.startsWith( "update" ) )
		{
			return new UpdatePackingSlipAction().execute( mapping, form, request, response );
		}
        else if( action.equalsIgnoreCase( "EditShippingAddress") || action.equalsIgnoreCase( "AddShippingAddress") || action.equalsIgnoreCase( "SaveShippingAddress") )
		{
			return new EditPackingSlipShippingAddressAction().execute( mapping, form, request, response );
		}

		return null;
	}


    private HashMap getFinalInventoryMapByCustomerShippingId( HashMap finalInventoryMap )
    {
        HashMap finalInventoryMapByCustomerShippingId = new HashMap();
        ArrayList dataList = null;
        FinalInventoryData inventoryData = null;
        Iterator it = finalInventoryMap.keySet().iterator();
        while ( it.hasNext() )
        {
			dataList = (ArrayList)finalInventoryMap.get( it.next() );

			if ( dataList.size() >= 1 )
			{
				inventoryData 	= (FinalInventoryData)dataList.get( 0 );
				finalInventoryMapByCustomerShippingId.put( inventoryData.getCsLineItemId()+"", dataList );
			}
        }

		return finalInventoryMapByCustomerShippingId;
    }

    public String formatAsHTML (String host, PackingSlipForm packingSlipForm, HashMap finalInventoryMap ) {

		StringBuffer buf 			= new StringBuffer (2098);
		String backgroundImage 		= "";
		String MFG_PART_NUMBER_KEY 	= "";
		String MKT_PART_NUMBER_KEY 	= "";
		String CUSTOMER_PART_NUMBER_KEY = "";
        String WEIGHT_MEASUREMENT = "";
        String CUSTOMER_REQUEST_DATE_KEY = "";
        String SCHEDULE_DATE_KEY = "";
        String SIGNATURE = "";

        try
		{
			 MFG_PART_NUMBER_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.mfgPartNumber" );
		}
		catch ( NullPointerException e )
		{
			 MFG_PART_NUMBER_KEY = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
		}
        try
		{
			 MKT_PART_NUMBER_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.mktgPartNumber" );
		}
		catch ( NullPointerException e )
		{
			 MKT_PART_NUMBER_KEY = Labels.DEFAULT_MKTG_PART_NUMBER_LABEL;
		}
		try
		{
			 CUSTOMER_PART_NUMBER_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.customerPartNumber" );
		}
		catch ( NullPointerException e )
		{
			 CUSTOMER_PART_NUMBER_KEY = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
		}

		if ( Constants.CUSTOMER_SHIPPING_STATUS_CANCELLED.equalsIgnoreCase ( packingSlipForm.getStatus() ) )
		{
			backgroundImage = "http://" + host + "/" + ConfigManager.getChipTracContext() + "/jsp/includes/images/cancelled_icon.gif";
		}

        try
		{
			 WEIGHT_MEASUREMENT = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.packingSlip.WeightMeasurements" );
		}
		catch ( NullPointerException e )
		{
			 WEIGHT_MEASUREMENT = Labels.DEFAULT_WEIGHT_MEASUREMENT_LABEL;
		}

        try
		{
			 CUSTOMER_REQUEST_DATE_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.packingSlip.CustomerRequestDate" );
		}
		catch ( NullPointerException e )
		{
			 CUSTOMER_REQUEST_DATE_KEY = Labels.DEFAULT_CUSTOMER_REQUEST_DATE_LABEL;
		}

        try
		{
			 SCHEDULE_DATE_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.packingSlip.ScheduleDate" );
		}
		catch ( NullPointerException e )
		{
			 SCHEDULE_DATE_KEY = Labels.DEFAULT_SCHEDULE_DATE_LABEL;
		}
        try
		{
			 SIGNATURE = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.signature" );
		}
		catch ( NullPointerException e )
		{
            SIGNATURE =  Labels.DEFAULT_SIGNATURE_LABEL;
        }

        buf.append ("<HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE>\n");
		buf.append ("<link href='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/stylesheets/scalarsoft.css' type='text/css' rel='stylesheet'>\n");
		buf.append ("</HEAD><BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>\n");
		buf.append ("<!-- body starts -->\n");
		// Body Starts
		buf.append ("<table border='0' width='90%' align='center'  background='"+backgroundImage+"'>\n");
		buf.append ("<tr><td align='center'>");
		buf.append ("<table width='100%' border='0' cellspacing='0'>");
			buf.append ("<TR><td width='35%' align='left' valign='top'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/scalar_logo.jpg' height='84' width='200' border='0' ></td>");
			buf.append ("<td width='35%' align='center' class='NArialL'><font class='NArialW'>Packing Slip</font></td>" );
            buf.append ("<td width='30%' align='right'>");
            buf.append ( "<table><tr><td align='left' class='NArialL'>" );
            buf.append ( packingSlipForm.getClientInfo().getClientName() );
            buf.append ( packingSlipForm.getClientAddrWithOutEmailObjFormatted() );
			buf.append ( "</td></tr></table>");
            buf.append ( "</td></TR>");
		buf.append ("</table></td></tr>");
		buf.append ("<tr><td align='center'>");
			buf.append ("<table width='100%' border='0' class='NArialRS' bordercolor='#000000' cellspacing='0'>");
			buf.append ("<tr><td bgcolor='#FFFFEE' class='NArialRS' width='40%' height='100%' align='left'>");
			buf.append ("<table width='100%' height='100%' class='NArialRS' border='1' bordercolor='#000000' cellspacing='0' height='100%'>");
			buf.append ("<tr height='30'><td class='NArialR' bgcolor='#DEE1E2' >Ship From:</td></tr>");
			buf.append ("<tr><td class='NArialRS' valign='top'>" );
            buf.append( packingSlipForm.getClientName() );//+ "<br>" );
			buf.append( packingSlipForm.getShippingVendorObjectFormatted() + " </td></tr></table></td>" );
			buf.append ("<td width='20%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'></td>");
			buf.append ("<td  width='40%' height='100%' bgcolor='#FFFFEE' class='NArialRS' align='right'>");
			buf.append ("<table width='100%' height='100%' class='NArialRS' border='1' bordercolor='#000000' cellspacing='0' height='100%'>");
			buf.append ("<tr height='30'><td class='NArialR' bgcolor='#DEE1E2' >Ship To:</td></tr>");
            buf.append ("<tr><td valign='top'>"); 
            /*if( packingSlipForm.getShippingAddressObject() != null )
            {
                if( ! packingSlipForm.getCustomerName().equals( packingSlipForm.getShippingAddressObject().getContactPerson() ) )
                    buf.append ( "<font class='NArialRS'>" + ((packingSlipForm.getCustomerName() == null) ? "" : packingSlipForm.getCustomerName()) + "</font>" );
            }
            else
            {
                buf.append ( "<font class='NArialRS'>" + ((packingSlipForm.getCustomerName() == null) ? "" : packingSlipForm.getCustomerName()) + "</font>" );
            }*/
			buf.append ("<font class='NArialRS'>");
			try
			{
				buf.append( packingSlipForm.getShippingAddressObjectFormatted() );
			}
			catch (Exception e)
			{
				System.out.println(" Exception in formatAsHtml: " +e);
			}
			buf.append ("</font></table></td></tr>");
		buf.append ("</table></td></tr>");

        buf.append ("<tr><td width='100%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='20'></td></tr>");
        buf.append ("<tr><td  width='100%'><font class='NArialR'><strong><u>Shipping Instructions:</u></strong></font></td></tr>\n");
        buf.append ("<tr><td  bgcolor='#DEE1E2'><font class='NArialRS'>" + ((packingSlipForm.getShippingInstructions() == null) ? "" : packingSlipForm.getShippingInstructions()) + "</font></td></tr>\n");
        buf.append ("<tr><td width='100%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='10'></td></tr>");
		buf.append ("<tr><td width='100%'>\n");
		buf.append ("<table border='1' width='100%' class='NArialRS' bordercolor='#000000' cellspacing='0'>\n");
		buf.append ("<TR>\n");
			buf.append ("<td width='12%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Customer PO#</td>\n");
			buf.append ("<td width='12%'  class='NArialR' align='center' bgcolor='#DEE1E2'>");

            if( packingSlipForm.getIsSample() )
            {
                buf.append("Sample Sales Order#");
            }
            else
            {
                buf.append("Sales Order#");
            }
            buf.append("</td>\n");

			buf.append ("<td width='12%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Packing Slip Label</td>\n");
			buf.append ("<td width='12%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Ship Date</td>\n");
			buf.append ("<td width='12%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Shipped Via</td>\n");
			buf.append ("<td width='10%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Way Bill</td>\n");
			buf.append ("<td width='10%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Del. Terms</td>");
			buf.append ("<td width='10%'   class='NArialR' align='center' bgcolor='#DEE1E2'># Cartons</td>");
            if( ConfigManager.getShowPackageDimensionInPackingSlip() )
            {
                buf.append ("<td width='10%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Net Weight ("+ ( ( packingSlipForm.getWeightType() == null) ? "&nbsp;" : packingSlipForm.getWeightType() ) + ")");
            }
            else
            {
                buf.append ("<td width='10%'  class='NArialR' align='center' bgcolor='#DEE1E2'>Weight ("+ ( ( packingSlipForm.getWeightType() == null) ? "&nbsp;" : packingSlipForm.getWeightType() ) + ")");
            }
        
            buf.append ("</td>");
		buf.append ("</tr>");
		buf.append ("<tr>");
			buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getCustomerPO() == null) ? "&nbsp;" : packingSlipForm.getCustomerPO() ) + "</td>" );
			buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getSalesOrderNumber() == null) ? "&nbsp;" : packingSlipForm.getSalesOrderNumber() ) + "</td>" );
			buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getLabel() == null ) ? "&nbsp;" : packingSlipForm.getLabel() ) + "</td>" );
			buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getShipDate() == null) ? "&nbsp;" : packingSlipForm.getShipDate() ) + "</td>" );
			buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getShippedVia() == null) ? "&nbsp;" : packingSlipForm.getShippedVia() ) + "&nbsp;</td>" );
			buf.append ( "<td align='center' bgcolor='#FFFFEE'>" );
			buf.append ( "<table class='NArialRS'>" );
			if( packingSlipForm.getTracking() != null && packingSlipForm.getTracking().length > 0 )
			{
				for ( int i = 0; i < packingSlipForm.getTracking().length; i++ )
				{
					buf.append ( "<tr><td>" + packingSlipForm.getTracking()[i] + "</td></tr>" );
				}
			}
			else
			{
				buf.append ( "<tr><td>&nbsp;</td></tr>" );
			}
			buf.append ( "</table>" );
			buf.append ( "</td>" );
			buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getFob() == null) ? "&nbsp;" : packingSlipForm.getFob() ) + "</td>" );
			buf.append ( "<td align='center'  bgcolor='#FFFFEE'>" + ( ( ( packingSlipForm.getNoOfBoxes() == null ) || ( packingSlipForm.getNoOfBoxes().equals( "0" ) ) ) ? "&nbsp;" : packingSlipForm.getNoOfBoxes() )+ "</td>" );
			String weight = packingSlipForm.getWeight();
			String grossWeight = packingSlipForm.getGrossWeight();
			buf.append ( "<td align='center' bgcolor='#FFFFEE'>&nbsp;" + weight + "</td>" );
            buf.append ( "</tr></table></td></tr>" );

		/*buf.append ("<tr><td  width='100%'><font class='NArialR'><strong><u>Shipping Instructions:</u></strong></font></td></tr>\n");*/
		/*buf.append ("<tr><td  bgcolor='#DEE1E2'><font class='NArialRS'>" + ((packingSlipForm.getShippingInstructions() == null) ? "" : packingSlipForm.getShippingInstructions()) + "</font></td></tr>\n");*/
        buf.append ("<tr><td ><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='10' ></td></tr>\n");
        if( ConfigManager.getShowPackageDimensionInPackingSlip() )
        {
            buf.append ( "<tr><td colspan=4>" );
            buf.append ( "<table border='1' width='100%' class='NArialRS' bordercolor='#000000' cellspacing='0'>" );
            buf.append ( "<tr>" );
            buf.append ( "<td width='10%' align='center' bgcolor='#DEE1E2' class='NArialR'>Country of Origin(Fab)</td>" );
            buf.append ( "<td width='10%' align='center' bgcolor='#DEE1E2' class='NArialR'>Country of Origin(Assy)</td>" );
            buf.append ( "<td width='10%' align='center' bgcolor='#DEE1E2' class='NArialR'>MAWB No</td>" );
            buf.append ( "<td width='10%' align='center' bgcolor='#DEE1E2' class='NArialR'>HAWB No</td>" );
            buf.append ( "<td width='10%' align='center' bgcolor='#DEE1E2' class='NArialR'>Flight-1 No</td>" );
            buf.append ( "<td width='10%' align='center' bgcolor='#DEE1E2' class='NArialR'>Flight-2 No</td>" );
            buf.append ( "<td width='10%' align='center' bgcolor='#DEE1E2' class='NArialR'>ETD</td>" );
            buf.append ( "<td width='10%' align='center' bgcolor='#DEE1E2' class='NArialR'>ETA</td>" );
            buf.append ( "<td width='10%' align='center' bgcolor='#DEE1E2' class='NArialR'>Package Dimension<br>(" + ( ( packingSlipForm.getUomPkgDimension() == null) ? "&nbsp;" : packingSlipForm.getUomPkgDimension() ) + ")</td>" );
            buf.append ( "<td width='10%' align='center' bgcolor='#DEE1E2' class='NArialR'>Gross Weight<br>(" + ( ( packingSlipForm.getWeightType() == null) ? "&nbsp;" : packingSlipForm.getWeightType() ) + ")</td>" );
            buf.append ( "</tr>" );
            buf.append ( "<tr>" );
            buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getCountryOfFabOrigin() == null) ? "&nbsp;" : packingSlipForm.getCountryOfFabOrigin() ) + "&nbsp;</td>" );
            buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getCountryOfAssyOrigin() == null) ? "&nbsp;" : packingSlipForm.getCountryOfAssyOrigin() ) + "&nbsp;</td>" );
            buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getMawb() == null) ? "&nbsp;" : packingSlipForm.getMawb() ) + "&nbsp;</td>" );
            buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getHawb() == null) ? "&nbsp;" : packingSlipForm.getHawb() ) + "&nbsp;</td>" );
            buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getFlightNumberOne() == null) ? "&nbsp;" : packingSlipForm.getFlightNumberOne() ) + "&nbsp;</td>" );
            buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getFlightNumberTwo() == null) ? "&nbsp;" : packingSlipForm.getFlightNumberTwo() ) + "&nbsp;</td>" );
            buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getEtd() == null) ? "&nbsp;" : packingSlipForm.getEtd() ) + "&nbsp;</td>" );
            buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getEta() == null) ? "&nbsp;" : packingSlipForm.getEta() ) + "&nbsp;</td>" );
            buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getPackageDimension() == null) ? "&nbsp;" : packingSlipForm.getPackageDimension() ) + "&nbsp;</td>" );
            buf.append ( "<td align='center' bgcolor='#FFFFEE'>" + ( ( packingSlipForm.getGrossWeight() == null) ? "&nbsp;" : packingSlipForm.getGrossWeight() ) + "&nbsp;</td>" );
            buf.append ( "</tr>" );
            buf.append ( "</table>" );
            buf.append ( "</td>" );
            buf.append ( "</tr>" );
        }
        buf.append ("<tr><td ><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='10' ></td></tr>\n");
        buf.append ("<tr><td  width='100%'><font class='NArialR'><strong><u>comments:</u></strong></font></td></tr>\n");
        buf.append ("<tr><td  bgcolor='#DEE1E2'><font class='NArialRS'>" + ((packingSlipForm.getComments() == null) ? "" : packingSlipForm.getComments().replaceAll( "\n", "<BR>" ) ) + "</font></td></tr>\n");
        buf.append ("<tr><td ><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='10' ></td></tr>\n");
		buf.append ("<tr><td  width='100%' >\n");
		buf.append ("<table border='0' width='100%' class='NArialRS' bordercolor='#000000' cellspacing='0'>\n");

		buf.append ("<tr><td  width='100%' >\n");
			buf.append ("<table border='1' width='100%' class='NArialRS' bordercolor='#000000' cellspacing='0'>\n");
				  buf.append ("<tr>\n");
					buf.append ("<td width='5%'  nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>PO Line<br> Item</font></td>");
					buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>"+ MKT_PART_NUMBER_KEY +"</font></td>");
                    if( packingSlipForm.getRecipientType()  != null && packingSlipForm.getRecipientType().equalsIgnoreCase("vendor") )
			        {
                        buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'> Shipped "+ MFG_PART_NUMBER_KEY +"</font></td>");
                    }
					buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>" + CUSTOMER_PART_NUMBER_KEY + "</font></td>");
					buf.append ("<td width='25%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Description</font></td>");
					buf.append ("<td width='5%'  nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>UOM</font></td>");
					buf.append ("<td width='9%'  nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>" + CUSTOMER_REQUEST_DATE_KEY +"</font></td>");
					buf.append ("<td width='9%'  nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>" + SCHEDULE_DATE_KEY + "</font></td>");
					buf.append ("<td width='6%'  nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Req Qty</font></td>");
					buf.append ("<td width='6%'  nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Qty Shipped</font></td>");
					buf.append ("<td width='15%' nowrap align='center' bgcolor='#DEE1E2' nowrap><font class='NArialR'>[Lot #] [Date Code] [Qty]</font></td>");
				buf.append ("</tr>\n");

		if ( finalInventoryMap == null )
		{
			finalInventoryMap = new HashMap();
		}

		CustomerShippingLineItems csLineItem 	= null;
		ArrayList finalInventoryList 			= null;
		FinalInventoryData finalInventoryData 	= null;
		HashMap customerShippingLotNumberMap 	= null;
		Iterator customerShippingLotNumbers 	= null;
		int finalInventoryListSize 				= -1;
		int size 								= packingSlipForm.getLineitems().size();
		CustomerShippingLotNumberData customerShippingLotNumberData = null;
        String shippedSKU = null;
        //ArrayList shippedSKUList = new ArrayList();
        String[] shippedSKUList = null;
		for ( int i = 0; i < size; i++ )
		{

			csLineItem 			= ( CustomerShippingLineItems ) packingSlipForm.getLineitems().get( i );
			finalInventoryList 	= ( ArrayList ) finalInventoryMap.get ( csLineItem.getLineItemId() + "" );
            //shippedSKUList = csLineItem.getQtyPulledSubstitutablePartNo();
            shippedSKUList = csLineItem.getShipped_Part_Number();
            try {
                 shippedSKU = csLineItem.getSubstitutablePartNumbersAsString( "<br>" );
            }
            catch (ScalarException se) {
                System.out.println ("Exception while parsing the shipping part numbers");
                se.printStackTrace();
            }
			String description 			= csLineItem.getCool_Description()  ;

			String customerPartNumber 	= csLineItem.getCustomer_Part_Number();
			String version 				= ( csLineItem.getSoftwareVersion() == null ? "" : csLineItem.getSoftwareVersion() );
			String units 				= ( csLineItem.getUnits() == null ? "" : csLineItem.getUnits() );

				buf.append ("<tr>\n");
					buf.append ("<td width='5%'  align='center' bgcolor='#FFFFEE'><font class='NArialRS'>");
						if( csLineItem.getCool_PO_Line_Item_No() == 0 )
						{
							buf.append ("&nbsp;");
						}
						else
						{
							buf.append ( csLineItem.getCool_PO_Line_Item_No() );
						}
					buf.append ("</font></td>\n");
					buf.append ("<td width='10%' nowrap align='left' bgcolor='#FFFFEE'><font class='NArialRS'>" + csLineItem.getMkt_Part_Number() + "</font></td>\n");
                    if( packingSlipForm.getRecipientType()  != null && packingSlipForm.getRecipientType().equalsIgnoreCase("vendor") )
			        {
                        buf.append ("<td width='10%' align='left'  valign='middle' bgcolor='#FFFFEE'>");
                        //buf.append ("<table border='0' width='100' bgcolor='#FFFFEE' class='viewTable'><tr><td align='left' bgcolor='#FFFFEE'><font class='NArialRS'>");
                        buf.append ("<table border='0' width='100%' bgcolor='#FFFFEE' class='viewTable'>");
                        if( shippedSKUList != null )
                        {
                            for ( int v = 0; v < shippedSKUList.length; v++ )
                            {
                                //shippedSKU = shippedSKUList.get( v ).toString();
                                shippedSKU = shippedSKUList[v];
                                if( shippedSKU != null && shippedSKU.trim().length() > 0 && ! csLineItem.getPart_Number().equalsIgnoreCase( shippedSKU )  )
                                {
                                    buf.append ( "<tr><td align='left' valign='middle' bgcolor='#FFFFEE'  class='NArialRS'>" + shippedSKU + "</td></tr>");
                                }
                                shippedSKU = "";
                            }
                        }
                        buf.append ( "</table></td>" );
                        //buf.append ( ( ( ( shippedSKU == null ) || ( shippedSKU.trim().length() == 0 ) ) ? "&nbsp;" : shippedSKU ) +"</font></td></tr></table></td>");
                    }
					buf.append ("<td width='10%' nowrap align='left' bgcolor='#FFFFEE'><font class='NArialRS'>" );
					buf.append ( ( ( ( customerPartNumber == null ) || ( customerPartNumber.trim().length() == 0 ) ) ? "&nbsp;" : customerPartNumber ) );
					buf.append ("</font></td>\n");
					buf.append ("<td width='25%' align='left' bgcolor='#FFFFEE'>");
					buf.append ("<table border='0' width='100' bgcolor='#FFFFEE' class='viewTable'><tr><td align='left' bgcolor='#FFFFEE'><font class='NArialRS'>");
					buf.append ( ( ( ( description == null ) || ( description.trim().length() == 0 ) ) ? "" : description ) +"</font></td></tr></table></td>");

					buf.append ("<td width='5%' align='left' bgcolor='#FFFFEE'><font class='NArialRS'>" + ( ( units.trim().length() == 0 )  ? "&nbsp;" : units ) + "</font></td>\n");
					buf.append ("<td width='9%' align='center' bgcolor='#FFFFEE'><font class='NArialRS'>" + ( csLineItem.getCool_Requested_Date() != null ? csLineItem.getCool_Requested_Date() : "&nbsp;") + "&nbsp;</font></td>\n");
					
		            // Showing the Revised Schedule Date if the schedule date is revised
		            String scheduleDate = "";
		            if ( csLineItem.getCool_Revised_Date() != null )
		            {
		            	scheduleDate = csLineItem.getCool_Revised_Date();
		            }
		            else if ( csLineItem.getCool_Schedule_Date() != null )
		            {
		            	scheduleDate = csLineItem.getCool_Schedule_Date();
		            }
		            else
		            {
		            	scheduleDate = "&nbsp;";
		            }
		            
					buf.append ("<td width='9%' align='center' bgcolor='#FFFFEE'><font class='NArialRS'>" + ( scheduleDate ) + "&nbsp;</font></td>\n");
					buf.append ("<td width='6%' align='right' bgcolor='#FFFFEE'><font class='NArialRS'>" + StringUtils.formatUnits ( csLineItem.getCool_Qty() ) + "</font></td>\n");
					buf.append ("<td width='6%' align='right' bgcolor='#FFFFEE'><font class='NArialRS'>");

					if (csLineItem != null) buf.append ( StringUtils.formatUnits ( csLineItem.getQtyPulled() ) );
					buf.append ("</font></td>\n");

					buf.append ("<td width='15%' align='center' bgcolor='#FFFFEE' nowrap><font class='NArialR'>\n");
					buf.append ("<table bgcolor='#FFFFEE' border='1' bordercolor='#000000' cellspacing='0'  cellpadding='0' width='100%' >\n");

					String lotNumbers = "";

					try {
						//customerShippingLotNumberMap = PackingSlipDAO.loadCustomerShippingLotNumberData (packingSlipForm.getCustomerShippingId(), csLineItem.getLineItemId());
                        customerShippingLotNumberMap = NewPackingSlipDAO.loadCustomerShippingLotNumberData ( packingSlipForm.getCustomerShippingId(), csLineItem.getLineItemId() );
					}
					catch (ScalarException se) {
						System.out.println ("Exception while load customer shipping lot number data from database");
						se.printStackTrace();
					}

					if (customerShippingLotNumberMap == null) customerShippingLotNumberMap = new HashMap();

					customerShippingLotNumbers = customerShippingLotNumberMap.values().iterator();

					int qtyPull = 0;
					while (customerShippingLotNumbers.hasNext()) {
						customerShippingLotNumberData = (CustomerShippingLotNumberData) customerShippingLotNumbers.next();
						qtyPull = customerShippingLotNumberData.getQtyPull();

						if (qtyPull > 0)
                        {
							buf.append ("<tr>");
							if( ConfigManager.getShowFabLotNumberInPackingSlip() )
							{
								buf.append ("<td nowrap align='left'><font class='NArialRS'>" + customerShippingLotNumberData.getFabLotNumber() + "</font></td>");
							}
							else
							{
								buf.append ("<td nowrap align='left'><font class='NArialRS'>" + customerShippingLotNumberData.getLotNumber() + "</font></td>");
							}
							
                            buf.append ("<td nowrap align='left'><font class='NArialRS'>" + ( ( customerShippingLotNumberData.getDateCode() != null && customerShippingLotNumberData.getDateCode().length() > 0 ) ? customerShippingLotNumberData.getDateCode() : "&nbsp;" ) + "</font></td>");
							buf.append ("<td nowrap align='right'><font class='NArialRS'>" + qtyPull + "</font></td>");
							buf.append ("</tr>");
						}
					}

					buf.append ("</table></font></td>\n");
			buf.append ("</tr>\n");
		}

		buf.append ("</table></td></tr>\n");

		buf.append ("<tr><td ><BR></td></tr>\n");
		buf.append ("<tr><td colspan=4>");
		buf.append("<table border='0' width='100%' align='center' bordercolor='#FFFFFF' cellspacing='2' cellpadding='2'>");
		buf.append("<tr><td align='center'><font class='NArialView'>CERTIFICATE OF COMPLIANCE</font></td></tr>");
		buf.append("<tr><td><font class='NArialRS'>THIS PRODUCT SHIPPED HERE WITH HAVE BEEN INSPECTED AND COMPLY WITH THE "+
		"REQUIREMENTS OF YOUR PURCHASE ORDER TO THE EXTENT THAT SUCH REQUIREMENT HAVE BEEN ACCEPTED AND ACKNOWLEDGED BY "+
		packingSlipForm.getClientInfo().getClientName()+
		" SUBSTANTIATING INSPECTION AND TEST ON THAT FILE.</font>");
        buf.append ( "<br><br><font class='NArialRS'>WE CERTIFY THAT INSPECTION EVIDENCE, INCLUDING TEST DATA,NECESSARY TO SUBSTANTIATE THIS CERTIFICATION IS AVAILABLE FROM OUR FILES.</font></td></tr>");
		buf.append ("<tr><td align='center'><font class='NArialRS'><B>THANK YOU FOR YOUR BUSINESS!</B></font></td></tr></table>");
		buf.append ("</td></tr>\n");
		buf.append ("<tr><td ><BR></td></tr>\n");
        buf.append ("<tr>\n");
        buf.append ("<td colspan='4'  width='100%'>\n");
        buf.append ("<table width='100%'>\n");
        buf.append ("<tr>\n");
			buf.append ("<td width='30%' class='NArialR'>Packed By:</td>\n");
			buf.append ("<td width='20%' class='NArialR'>\n");
			buf.append ("<font class='signatureWithoutUnderLine'>\n");
            buf.append ( SIGNATURE );
            buf.append ("</font>\n");
            buf.append ( "<br>__________________________________________\n" );
            buf.append ( "<br>Name/Signature\n" );
			buf.append ("</td>\n");
			buf.append ("<td>&nbsp;</td>\n");
		buf.append ("</tr>\n");
        buf.append ("<tr><td colspan='3'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='5'></td></tr>\n");
        buf.append ("<tr>\n");
			buf.append ("<td width='30%' class='NArialR'>Checked By:</td>\n");
			buf.append ("<td width='20%' class='NArialR'>\n");
			buf.append ("<font class='signatureWithoutUnderLine'>\n");
            buf.append ( SIGNATURE );
            buf.append ("</font>\n");
            buf.append ( "<br>__________________________________________\n" );
            buf.append ( "<br>Name/Signature\n" );
			buf.append ("</td>\n");
			buf.append ("<td>&nbsp;</td>\n");
		buf.append ("</tr>\n");
        buf.append ("</table></td></tr>\n");

        /*buf.append ("<tr><td width='100%'><table width='100%'>\n");
		buf.append ("<tr>\n");
			buf.append ("<td class='NArialR' width='35%'><b>Checked By</b>\n");
			buf.append ("<td class='NArialR' width='35%'>__________________________________________<br> <b>Name/Signature</b>");
			buf.append ("<td width='30%'>&nbsp;</td>");
		buf.append ("</table></td></tr>\n");
		buf.append ("<tr><td width='100%'><table width='100%'>\n");
		buf.append ("<tr>\n");
			buf.append ("<td class='NArialR' width='35%'>&nbsp;\n");
			buf.append ("<td class='NArialR' width='35%'>__________________________________________<br> <b>Name/Signature</b> ");
			buf.append ("<td width='30%'>&nbsp;</td>\n");
		buf.append ("</tr>\n");
        buf.append ("</table></td>\n");*/

        /*buf.append ("</tr>\n");*/
		buf.append ("</table>\n");
		buf.append ("<!-- till here -->\n");
		buf.append ("</body>\n");

		buf.append ("</html>\n");

		return buf.toString();
	}


	/**
	 *@return creates a temporary PackingSlip HTML form, and returns the absolute path
	 */
	public String getPackingSlipAsHtmlFile( String host, PackingSlipForm packingSlipForm, HashMap finalInventoryMap)
	{
		String filePath = null;
		String psAsHtml = formatAsHTML( host, packingSlipForm, finalInventoryMap );

		if( psAsHtml == null )
		{
			return filePath;
		}

		FileWriter fWriter = null;
		File psAttachment = null;

		try {
			// CREATE TEMPORARY ATTACHMENT FILE
			String mailingTempDir = ConfigManager.getMailerTempDir();
			File tempDir = new File (mailingTempDir).getCanonicalFile();
			tempDir.mkdir();

			String psAttachmentFileName = packingSlipForm.getLabel();
			if( ( psAttachmentFileName != null ) && ( psAttachmentFileName.startsWith( "PS-" ) ) )
			{
				psAttachmentFileName = psAttachmentFileName.substring( 3 );
			}

			psAttachmentFileName = "Packing_Slip_SO_" + psAttachmentFileName + ".html";

			psAttachment = new File( tempDir.getCanonicalPath(), psAttachmentFileName );
			psAttachment.deleteOnExit();

			if( ( psAttachment.exists() == true ) || ( psAttachment.createNewFile() == true ) )
			{
				fWriter = new FileWriter (psAttachment, false);

				fWriter.write( psAsHtml );

				fWriter.close();
				fWriter = null;

				filePath = psAttachment.getAbsolutePath();
			}
		}
		catch( Exception e )
		{
			System.out.println( "Exception while creating packingslip html file");
			e.printStackTrace();
		}
		finally
		{
			if( fWriter != null )
			{
				try
				{
					fWriter.close();
					fWriter = null;
				}
				catch( IOException ignore ){}
			}
		}
		return filePath;
	}

    public String getPackingSlipAsPDFFile(String host, PackingSlipForm packingSlipForm, HashMap finalInventoryMap )
    {
		String fileXMLPath 		= null;
		String filePDFPath 		= null;
		String fileXSLTPath 	= null;
		FileWriter fWriter 		= null;
		File psPDFAttachment 	= null;
		File psXML 				= null;
        OutputStreamWriter out  = null;
        String psAsXML 			= formatAsXML( host, packingSlipForm, finalInventoryMap );

		if( psAsXML == null )
		{
			return fileXMLPath;
		}

		try
		{
			String mailingTempDir 		= ConfigManager.getMailerTempDir();
			File tempDir 				= new File ( mailingTempDir ).getCanonicalFile();
			String psAttachmentFileName = packingSlipForm.getLabel();
			String xmlFileName 			= "Packing_Slip_SO_" + psAttachmentFileName + ".xml";
			String  xsltFileName		= ConfigManager.getPackingSlipXml2PdfXslFile();
			String psAttachmentPDFFileName = "Packing_Slip_SO_" + psAttachmentFileName + ".pdf";

			tempDir.mkdir();

			if( ( psAttachmentFileName != null ) && ( psAttachmentFileName.startsWith( "PS-" ) ) )
			{
				psAttachmentFileName = psAttachmentFileName.substring( 3 );
			}

			psXML = new File( tempDir.getCanonicalPath(), xmlFileName );
			psXML.deleteOnExit();

			psPDFAttachment = new File( tempDir.getCanonicalPath(), psAttachmentPDFFileName );
			psPDFAttachment.deleteOnExit();

			if( ( psXML.exists() == true ) || ( psXML.createNewFile() == true ) )
			{
				/*fWriter = new FileWriter ( psXML, false);
				fWriter.write ( psAsXML );
				fWriter.close();
				fWriter = null*/;

                out = new OutputStreamWriter( new FileOutputStream( psXML ), "UTF-8" );

                out.write ( psAsXML );
                out.close ();
                out = null;


                fileXMLPath = psXML .getCanonicalPath() .toLowerCase();
				filePDFPath = psPDFAttachment .getCanonicalPath() .toLowerCase();
				boolean success = PDFGenerator.convertXML2PDF( fileXMLPath, xsltFileName, filePDFPath );
			}
		}
		catch( Exception e )
		{
			System.out.println( "Exception while creating packingslip PDF file");
			e.printStackTrace();
		}
		finally
		{
			if( fWriter != null )
			{
				try
				{
					fWriter.close();
					fWriter = null;
				}
				catch( IOException ignore ){}
			}
            if( out != null )
			{
				try
				{
					out.close();
					out = null;
				}
				catch( IOException ignore ){}
			}
        }

		return filePDFPath;
    }


	public String formatAsXML ( String host, PackingSlipForm packingSlipForm, HashMap finalInventoryMap ) {

		StringBuffer buf 			= new StringBuffer ( 2098 );
		String imagesDirLocation 	= ConfigManager.getChipTracImagesDir();
		String scalarLogo 			= ConfigManager.getScalarLogo();
		String crossCancel 			= ConfigManager.getCrossCanelImage();
		String contactPerson 		= "";
		String weight 				= "";
        String WEIGHT_MEASUREMENT = "";
        String CUSTOMER_REQUEST_DATE_KEY ="";
        String SCHEDULE_DATE_KEY = "";
        String SIGNATURE = "";

        try
		{
			 WEIGHT_MEASUREMENT = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.packingSlip.WeightMeasurements" );
		}
		catch ( NullPointerException e )
		{
			 WEIGHT_MEASUREMENT = Labels.DEFAULT_WEIGHT_MEASUREMENT_LABEL;
        }
        try
		{
			 CUSTOMER_REQUEST_DATE_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.packingSlip.CustomerRequestDate" );
		}
		catch ( NullPointerException e )
		{
			 CUSTOMER_REQUEST_DATE_KEY = Labels.DEFAULT_CUSTOMER_REQUEST_DATE_LABEL;
		}

        try
		{
			 SCHEDULE_DATE_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.packingSlip.ScheduleDate" );
		}
		catch ( NullPointerException e )
		{
			 SCHEDULE_DATE_KEY = Labels.DEFAULT_SCHEDULE_DATE_LABEL;
		}

        try
		{
			 SIGNATURE = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.signature" );
		}
		catch ( NullPointerException e )
		{
            SIGNATURE =  Labels.DEFAULT_SIGNATURE_LABEL;
        }

        buf.append ( "<?xml version='1.0' encoding='UTF-8'?>\n" );

		if ( Constants.CUSTOMER_SHIPPING_STATUS_CANCELLED.equalsIgnoreCase ( packingSlipForm.getStatus() ) )
		{
			buf.append ( "<packingSlip cancel='1'> \n" );
		}
		else
		{
			buf.append ( "<packingSlip cancel='0'> \n" );
		}

		try
		{
			contactPerson = packingSlipForm.getContactPerson();
			if ( ( contactPerson == null ) || ( ( contactPerson != null ) && ( contactPerson.equalsIgnoreCase ( "null" ) ) ) )
			{
				contactPerson = "";
			}
			else
			{
				contactPerson = packingSlipForm.getContactPerson();
			}
		}
		catch(Exception e)
		{
			contactPerson = "";
		}
        buf.append ( "<salesOrderFieldHeading>");
        if( packingSlipForm.getIsSample())
        {
            buf.append("Sample Sales Order#");
        }
        else
        {
            buf.append("Sales Order#");
        }
        buf.append ( "</salesOrderFieldHeading>\n");

		buf.append ( "<images>\n" );
		buf.append ( "<logo>"+imagesDirLocation + scalarLogo +"</logo> \n" );
		buf.append ( "<cancelImage>"+imagesDirLocation+crossCancel+"</cancelImage> \n" );
		buf.append ( "</images>\n" );
		buf.append ( "<selfAddress> \n" );
        buf.append( "<cName><![CDATA[" + packingSlipForm.getClientInfo().getClientName().toUpperCase() + "]]></cName>");
        buf.append ( "<name><![CDATA[" ) .append( packingSlipForm.getClientInfo().getClientName() ) .append( "]]></name> \n" );
		buf.append ( packingSlipForm.getClientAddressXMLFormatted() );
		buf.append ( "</selfAddress> \n" );

		buf.append ( "<shipFromAddress> \n" );

		buf.append ( "<name><![CDATA[" ) .append( packingSlipForm.getClientName() ) .append( "]]></name> \n" );
		buf.append ( packingSlipForm.getShippingVendorAddressXMLFormatted() );
		buf.append ( "</shipFromAddress> \n" );

		buf.append ( "<shipToAddress> \n" );
        if( packingSlipForm.getShippingAddressObject() != null )
        {
            if( ! packingSlipForm.getCustomerName().equals( packingSlipForm.getShippingAddressObject().getContactPerson() ) )
                buf.append ( "<name><![CDATA[" ) .append( (packingSlipForm.getCustomerName() == null) ? "" : packingSlipForm.getCustomerName() ) .append( "]]></name> \n" );
        }
        else
        {
            buf.append ( "<name><![CDATA[" ) .append( (packingSlipForm.getCustomerName() == null) ? "" : packingSlipForm.getCustomerName() ) .append( "]]></name> \n" );
        }

		//buf.append ( "<contactPerson><![CDATA[" ) .append( (contactPerson.trim().length() == 0 ) ? "" : contactPerson ) .append( " ]]></contactPerson> \n" ); Commented by Krishna Prasad on 28 May 2004
		try
		{
			buf.append( packingSlipForm.getShippingAddressXMLFormatted() );
		}
		catch (Exception e)
		{
			buf.append ( "<address1/> \n" );
			buf.append ( "<address2/> \n" );
			buf.append ( "<address3/> \n" );
			buf.append ( "<phone/> \n" );
			buf.append ( "<fax/> \n" );
			System.out.println(" Exception in formatAsXML: " +e);
		}
		buf.append ( "</shipToAddress> \n" );


        buf.append("<ShippingInstructions><![CDATA[");
        buf.append(((packingSlipForm.getShippingInstructions() == null) ? "" : packingSlipForm.getShippingInstructions().trim()));
        buf.append("]]></ShippingInstructions> \n");


        buf.append ( "<information> \n" );
		buf.append ( "<customerPO><![CDATA[" ) .append ( (packingSlipForm.getCustomerPO() == null) ? "" : packingSlipForm.getCustomerPO() ) .append ( "]]></customerPO> \n" );
		buf.append ( "<salesOrder><![CDATA[" ) .append ( (packingSlipForm.getSalesOrderNumber() == null) ? "" : packingSlipForm.getSalesOrderNumber() ) .append ("]]></salesOrder> \n");
		buf.append ( "<packingSlipLabel><![CDATA[" ) .append ( (packingSlipForm.getLabel() == null) ? "" : packingSlipForm.getLabel() ) .append ("]]></packingSlipLabel> \n");
		buf.append ( "<actualShipDate><![CDATA[" ) .append( (packingSlipForm.getShipDate() == null) ? "" : packingSlipForm.getShipDate() ) . append ( "]]></actualShipDate> \n" );
		buf.append ( "<shippedVia><![CDATA[" ) .append ( (packingSlipForm.getShippedVia() == null) ? "" : packingSlipForm.getShippedVia() ) .append( "]]></shippedVia> \n" );
		if( packingSlipForm.getTracking() != null && packingSlipForm.getTracking().length > 0 )
		{
			for ( int i = 0; i < packingSlipForm.getTracking().length; i++ )
			{
				buf.append ( "<freightTracking>\n");
				buf.append ( "<tracking>\n<![CDATA[" );
				buf.append ( packingSlipForm.getTracking()[i] + "\n" );
				buf.append ( "]]></tracking>\n" );
				buf.append ( "</freightTracking> \n" );
			}
		}
		else
		{
			buf.append ( "<freightTracking>\n");
			buf.append ( "<tracking>\n<![CDATA[ ]]></tracking> \n" );
			buf.append ( "</freightTracking> \n" );
		}

		buf.append ( "<delTerms><![CDATA[" ) .append ( (packingSlipForm.getFob() == null) ? "" : packingSlipForm.getFob() ) .append ( "]]></delTerms> \n" );
		buf.append ( "<cartons><![CDATA[" ) .append ( ( ( packingSlipForm.getNoOfBoxes() == null ) || ( packingSlipForm.getNoOfBoxes().equals("0") ) )? "" : packingSlipForm.getNoOfBoxes() ) .append ( "]]></cartons> \n" );
		weight = packingSlipForm.getWeight().trim();

        buf.append ( "<weight><![CDATA[" ).append (  weight ) .append ( " ]]></weight> \n" );
        buf.append ( "<grossWeight><![CDATA[" ).append (  packingSlipForm.getGrossWeight() ).append ( " ]]></grossWeight> \n" );
        buf.append ( "<weightMeasurement><![CDATA[" ).append (  (packingSlipForm.getWeightType() == null) ? "" : packingSlipForm.getWeightType() ) .append ( "]]></weightMeasurement> \n" );
        buf.append ( "<packageDimension><![CDATA[" ).append (  (packingSlipForm.getPackageDimension() == null) ? "" : packingSlipForm.getPackageDimension() ) .append ( " ]]></packageDimension> \n" );
        buf.append ( "<showPackageInformation><![CDATA[").append ( ( ConfigManager.getShowPackageDimensionInPackingSlip() ) ? "true" : "false" ) .append ("]]></showPackageInformation> \n" );
        buf.append ( "<countryOfOriginFab><![CDATA[" ).append (  (packingSlipForm.getCountryOfFabOrigin() == null) ? "" : packingSlipForm.getCountryOfFabOrigin() ) .append ( " ]]></countryOfOriginFab> \n" );
        buf.append ( "<countryOfOriginAssm><![CDATA[" ).append (  (packingSlipForm.getCountryOfAssyOrigin() == null) ? "" : packingSlipForm.getCountryOfAssyOrigin() ) .append ( " ]]></countryOfOriginAssm> \n" );
        buf.append ( "<uomPackageDimension><![CDATA[" ).append (  (packingSlipForm.getUomPkgDimension() == null) ? "" : packingSlipForm.getUomPkgDimension() ) .append ( "]]></uomPackageDimension> \n" );
        buf.append ( "<mawbNo><![CDATA[" ).append (  (packingSlipForm.getMawb() == null) ? "" : packingSlipForm.getMawb() ) .append ( " ]]></mawbNo> \n" );
        buf.append ( "<hawbNo><![CDATA[" ).append (  (packingSlipForm.getHawb() == null) ? "" : packingSlipForm.getHawb() ) .append ( " ]]></hawbNo> \n" );
        buf.append ( "<flightNoOne><![CDATA[" ).append (  (packingSlipForm.getFlightNumberOne() == null) ? "" : packingSlipForm.getFlightNumberOne() ) .append ( " ]]></flightNoOne> \n" );
        buf.append ( "<flightNoTwo><![CDATA[" ).append (  (packingSlipForm.getFlightNumberTwo() == null) ? "" : packingSlipForm.getFlightNumberTwo() ) .append ( " ]]></flightNoTwo> \n" );
        buf.append ( "<etd><![CDATA[" ).append (  (packingSlipForm.getEtd() == null) ? "" : packingSlipForm.getEtd() ) .append ( " ]]></etd> \n" );
        buf.append ( "<eta><![CDATA[" ).append (  (packingSlipForm.getEta() == null) ? "" : packingSlipForm.getEta() ) .append ( " ]]></eta> \n" );
        buf.append ( "<signature><![CDATA[" ).append (  SIGNATURE ) .append ( " ]]></signature> \n" );

        buf.append ( "</information> \n" );

		/*buf.append ( "<ShippingInstructions><![CDATA[" );
		buf.append ( ( ( packingSlipForm.getShippingInstructions() == null ) ? "" : packingSlipForm.getShippingInstructions().trim() ) );
		buf.append ( "]]></ShippingInstructions> \n" );*/
        
        buf.append ( "<Comments><![CDATA[" );
		buf.append ( ( ( packingSlipForm.getComments() == null ) ? "" : packingSlipForm.getComments().trim() ) );
		buf.append ( "]]></Comments> \n" );

		buf.append ( "<lineItems> \n" );
		String mfgPartTitle = "";
		String mktPartTitle = "";
		try
		{
			mfgPartTitle = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.mfgPartNumber");
		}
		catch( NullPointerException e )
		{
			mfgPartTitle = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
		}
        try
		{
			mktPartTitle = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.mktgPartNumber");
		}
		catch( NullPointerException e )
		{
			mktPartTitle = Labels.DEFAULT_MKTG_PART_NUMBER_LABEL;
		}
		buf.append ( "<mfgPartTitle><![CDATA[");
		buf.append ( mfgPartTitle );
		buf.append ( "]]></mfgPartTitle> \n" );
        buf.append ( "<mktPartTitle><![CDATA[");
		buf.append ( mktPartTitle );
		buf.append ( "]]></mktPartTitle> \n" );
        buf.append ( "<skuPartTitle><![CDATA[");
        if( packingSlipForm.getRecipientType()  != null && packingSlipForm.getRecipientType().equalsIgnoreCase("vendor") )
        {
            buf.append ("Shipped " + mfgPartTitle );
        }
       buf.append ( "]]></skuPartTitle> \n" );

        buf.append ("<crdTitle><![CDATA[" + CUSTOMER_REQUEST_DATE_KEY + "]]></crdTitle>" );
        buf.append ("<schDateTitle><![CDATA[" + SCHEDULE_DATE_KEY + "]]></schDateTitle>" );

        if ( finalInventoryMap == null )
		{
			finalInventoryMap = new HashMap();
		}

		CustomerShippingLineItems csLineItem 	= null;
		HashMap customerShippingLotNumberMap 	= null;
		Iterator customerShippingLotNumbers 	= null;
		ArrayList finalInventoryList 			= null;
		FinalInventoryData finalInventoryData 	= null;
		int finalInventoryListSize 				= -1;
		int size 								= packingSlipForm.getLineitems().size();
		CustomerShippingLotNumberData customerShippingLotNumberData = null;
        String shippedSKU = null;
        LabelValueBean lvb = null;
        //ArrayList shippedSKUList = new ArrayList();
        String[] shippedSKUList = null;

		for ( int i = 0; i < size; i++ )
		{
			csLineItem 					= ( CustomerShippingLineItems ) packingSlipForm.getLineitems().get( i );
			finalInventoryList 			= ( ArrayList ) finalInventoryMap.get ( csLineItem.getLineItemId() + "" );
			String description 			= csLineItem.getCool_Description()  ;
			String customerPartNumber 	= csLineItem.getCustomer_Part_Number();
			String version 				= ( csLineItem.getSoftwareVersion() == null ? "" : csLineItem.getSoftwareVersion() );
			String units 				= ( csLineItem.getUnits() == null ? "" : csLineItem.getUnits() );

            //shippedSKUList = csLineItem.getSubstitutablePartNumbers();
            //shippedSKUList = csLineItem.getQtyPulledSubstitutablePartNo();
            shippedSKUList = csLineItem.getShipped_Part_Number();

            buf.append ( "<lineItem> \n" );
            buf.append ( "<poLineItem><![CDATA[" );
            if( csLineItem.getCool_PO_Line_Item_No() == 0 )
                buf.append ("");
            else
                buf.append ( csLineItem.getCool_PO_Line_Item_No() );
            buf.append ( "]]></poLineItem> \n" );
            buf.append ( "<mfgPartNumber><![CDATA[" ) .append ( csLineItem.getPart_Number() ) . append( "]]></mfgPartNumber>\n" );
            buf.append ( "<mktPartNumber><![CDATA[" ) .append ( csLineItem.getMkt_Part_Number() ) . append( "]]></mktPartNumber>\n" );
            if( packingSlipForm.getRecipientType()  != null && packingSlipForm.getRecipientType().equalsIgnoreCase("vendor") )
            {
                if( shippedSKUList  != null )
                {
                    for ( int v = 0; v < shippedSKUList.length; v++ )
                    {
                        /*lvb =  ( LabelValueBean ) shippedSKUList.get( v );
                        shippedSKU = lvb.getLabel();
                        buf.append ( "<shippedSKUs>\n");
                        buf.append ( "<shippedSKU><![CDATA[" );
                        if( shippedSKU != null && shippedSKU.trim().length() > 0  )
                        {
                            buf.append ( shippedSKU );
                        }
                        else
                        {
                            buf.append ( "" );
                        }
                        buf.append ( "]]></shippedSKU> \n" );
                        buf.append ( "</shippedSKUs> \n" );
                        shippedSKU = "";*/
                        //shippedSKU = shippedSKUList.get( v ).toString();
                        shippedSKU = shippedSKUList[v];
                        buf.append ( "<shippedSKUs>\n");
                        buf.append ( "<shippedSKU><![CDATA[" );
                        if( shippedSKU != null && shippedSKU.trim().length() > 0 && ! csLineItem.getPart_Number().equalsIgnoreCase( shippedSKU )  )
                        {
                            buf.append ( shippedSKU );
                        }
                        else
                        {
                            buf.append ( "" );
                        }
                        buf.append ( "]]></shippedSKU> \n" );
                        buf.append ( "</shippedSKUs> \n" );
                        shippedSKU = "";
                    }
                }
                else
                {
                    buf.append ( "<shippedSKUs><shippedSKU><![CDATA[ ]]></shippedSKU></shippedSKUs> \n" );
                }
            }
            else
            {
                buf.append ( "<shippedSKUs>\n");
                buf.append ( "<shippedSKU>\n<![CDATA[ ]]></shippedSKU> \n" );
                buf.append ( "</shippedSKUs>\n" );
            }

            buf.append ( "<CustomerPartNumber><![CDATA[") .append ( customerPartNumber ) .append ("]]></CustomerPartNumber>\n");
            buf.append ( "<description><![CDATA[" );
            buf.append ( ( ( ( description == null ) || ( description.trim().length() == 0 ) ) ? "" : description.trim() ) );
            buf.append ( "]]></description>\n" );
            buf.append ( "<units><![CDATA[" ) .append ( ( ( units == null ) || ( units.trim().length() == 0 ) ) ? "" : units ) .append ( "]]></units>\n" );
            buf.append ( "<requestDate><![CDATA[" ) .append ( csLineItem.getCool_Requested_Date() != null ? csLineItem.getCool_Requested_Date() : "" ) .append ( "]]></requestDate>\n" );
            
            // Showing the Revised Schedule Date if the schedule date is revised
            String scheduleDate = "";
            if ( csLineItem.getCool_Revised_Date() != null )
            {
            	scheduleDate = csLineItem.getCool_Revised_Date();
            }
            else if ( csLineItem.getCool_Schedule_Date() != null )
            {
            	scheduleDate = csLineItem.getCool_Schedule_Date();
            }
            else
            {
            	scheduleDate = "";
            }
            
            //buf.append ( "<scheduleDate><![CDATA[" ) .append ( csLineItem.getCool_Schedule_Date() != null ? csLineItem.getCool_Schedule_Date() : "" ).append ( "]]></scheduleDate>\n" );
            
            buf.append ( "<scheduleDate><![CDATA[" ) .append ( scheduleDate ).append ( "]]></scheduleDate>\n" );
            buf.append ( "<reqQty><![CDATA[" ) .append ( StringUtils.formatUnits ( csLineItem.getCool_Qty() ) + "]]></reqQty>\n");
            buf.append ( "<qtyShipped><![CDATA[" );
            if (csLineItem != null) buf.append ( StringUtils.formatUnits ( csLineItem.getQtyPulled() ) );
            buf.append ( " ]]></qtyShipped>\n" );
            buf.append ( "<pulledLots>\n" );

            try
            {
                customerShippingLotNumberMap = NewPackingSlipDAO.loadCustomerShippingLotNumberData ( packingSlipForm.getCustomerShippingId(), csLineItem.getLineItemId() );
            }
            catch ( ScalarException se )
            {
                System.out.println ("Exception while load customer shipping lot number data from database");
                se.printStackTrace();
            }

            if ( customerShippingLotNumberMap == null )
            {
                customerShippingLotNumberMap = new HashMap();
            }

            customerShippingLotNumbers = customerShippingLotNumberMap.values().iterator();

            int qtyPull = 0;
            while ( customerShippingLotNumbers.hasNext() )
            {
                customerShippingLotNumberData = ( CustomerShippingLotNumberData ) customerShippingLotNumbers.next();
                qtyPull = customerShippingLotNumberData.getQtyPull();

                if ( qtyPull > 0 )
                {
                    buf.append ( "<lot>\n" );
					if( ConfigManager.getShowFabLotNumberInPackingSlip() )
					{
						buf.append ( "<lotName><![CDATA[ ").append ( customerShippingLotNumberData.getFabLotNumber() ).append ( "]]></lotName>\n" );
					}
					else
					{
						buf.append ( "<lotName><![CDATA[ ").append ( customerShippingLotNumberData.getLotNumber() ).append ( "]]></lotName>\n" );
					}
                    buf.append ( "<lotName><![CDATA[ ").append ( customerShippingLotNumberData.getLotNumber() ).append ( "]]></lotName>\n" );
                    buf.append ( "<lotDateCode><![CDATA[ ").append ( customerShippingLotNumberData.getDateCode() != null ? customerShippingLotNumberData.getDateCode() : "" ).append ( "]]></lotDateCode>\n" );
                    buf.append ( "<qty><![CDATA[" ) .append ( qtyPull ).append( " ]]></qty>\n" );
                    buf.append ("</lot>\n");
                }
            }
			buf.append ( "</pulledLots>\n" );
			buf.append ( "</lineItem>\n" );
		}

		buf.append ( "</lineItems>\n" );
		buf.append ( "</packingSlip>\n" );
		return buf.toString();
	}

    private HashMap loadNewFinalInventoryDataListMap ( HashMap existingFinalInventoryDataListMap , HashMap dbFinalInventoryDataListMap )
    {
    	ArrayList existingInventoryDataList = null;
        String lineItemId                   = null;
        HashMap inventoryDataListMap        = new HashMap();

    	if( dbFinalInventoryDataListMap != null && dbFinalInventoryDataListMap.isEmpty() == false )
    	{
            Iterator it = dbFinalInventoryDataListMap.keySet().iterator();

			while( it.hasNext() )
			{
				lineItemId	= (String) it.next() ;
                existingInventoryDataList = ( ArrayList ) existingFinalInventoryDataListMap.get( lineItemId );

                if( existingInventoryDataList != null && existingInventoryDataList.isEmpty() == false )
			    {
                    inventoryDataListMap.put( lineItemId , existingInventoryDataList  );
                }
                else
                {
                    inventoryDataListMap.put( lineItemId , dbFinalInventoryDataListMap.get( lineItemId )  );
                }
            }
    	}
        return inventoryDataListMap;
    }

    private ArrayList loadShippedPartNoFromInventoryDataList ( HashMap finalInventoryDataListMap , int lineItemId )
    {
    	ArrayList inventoryDataList     = null;
        HashMap inventoryDataListMap    = new HashMap();
        String[]  shippedPartNumbers    = null;
        ArrayList shippedPartNoList     = new ArrayList();
        FinalInventoryData  finalInventoryData  = null;

    	if( finalInventoryDataListMap != null && finalInventoryDataListMap.isEmpty() == false )
    	{
            inventoryDataList = ( ArrayList ) finalInventoryDataListMap.get( lineItemId + "" );
            for ( int i = 0; i < inventoryDataList.size() ; i++ )
            {
                finalInventoryData = ( FinalInventoryData ) inventoryDataList.get(i);
                if( finalInventoryData != null && finalInventoryData.getQuantityPull() > 0 )
                {
                    shippedPartNoList.add( finalInventoryData.getMktPartNumber() );
                }
            }
            /*shippedPartNumbers = new String[shippedPartNoList.size()];
            for( int i = 0 ; i < shippedPartNoList.size() ; i++ )
            {
                shippedPartNumbers[i] = ( String ) shippedPartNoList.get(i);
            } */
    	}

        return shippedPartNoList;
    }

}
